package is.common.watchdog;

import is.common.interfaces.DeactivationNeededThread;
import is.common.util.ObjectStreamer;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

/**
 * @author aspr0
 *         Date: 27.04.12
 *         Time: 22:45
 */
public class WatchdogServerSessionThread extends WatchdogAbstractThread implements DeactivationNeededThread
{
    private boolean watching = true;
    private Socket socket;
    
    public WatchdogServerSessionThread(Socket socket) throws IOException
    {
        super();
        this.socket = socket;
        ObjectInputStream objectInputStream = new ObjectInputStream(this.socket.getInputStream());
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(this.socket.getOutputStream());
        objectStreamer = new ObjectStreamer(objectInputStream, objectOutputStream);
    }

    @Override
    public void run()
    {
        while (watching)
        {
            try
            {
                objectStreamer.receiveString();
                objectStreamer.transmitObject(reply);
            }
            catch (SocketException e)
            {
                break;
            }
            catch (EOFException e)
            {
                break;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deactivate() throws IOException
    {
        watching = false;
        socket.setSoTimeout(0);
        socket.close();
    }
}
